﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace Common
{
    /// <summary>
    /// webservice访问类
    /// </summary>
    public class WebServiceHelper
    {
        public static string Post(string url, string requestXml)
        {
            string result = "";
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;

            try
            {
                //创建HttpWebRequest 实例
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                //发送请求
                webRequest.Method = "POST";
                //编码
                webRequest.ContentType = "text/xml;charset=UTF-8";
                //设置SOAPAction
                //webRequest.Headers.Add("SOAPAction", "");
                //字符转字节
                byte[] bytes = Encoding.UTF8.GetBytes(requestXml);
                using (Stream writer = webRequest.GetRequestStream())
                {
                    writer.Write(bytes, 0, bytes.Length);
                    writer.Flush();
                    writer.Close();
                }
                //返回 HttpWebResponse
                webResponse = webRequest.GetResponse() as HttpWebResponse;
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream rStream = webResponse.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(rStream, Encoding.UTF8))
                        {
                            result = sr.ReadToEnd();
                        }
                    }
                }
                else
                {
                    LogHelper.Error("连接错误：" + url);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("报错：" + ex);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse.Dispose();
                }
            }

            return result;
        }
    }
}
